'use strict';

const Controller = require('egg').Controller;
// 用户相关请求响应定义
const adminUserReqAndResp = require('../../entitys/reqAndResp/admin/adminUser');
const SysMacAddrService = require('../../model/SysMacAddrModel.js');
const sysMacAddrService = new SysMacAddrService();

/**
 * 创建者: rliang
 * 创建时间: 2019年08月19日 22:33:16
 * 功能描述: 登录相关操作控制器
 */
class LoginController extends Controller {

  async login() {
    const {
      ctx,
      service
    } = this;
    // 定义返回数据 data 中的数据结构
    const response = adminUserReqAndResp.login.response();
    // 检查请求参数并获得请求对象
    const request = ctx.request.getAndValidate_LoginRequest();
    // 将前端传过来的密码进行加密
    const encryPwd = ctx.encryOfMD5(request.loginPwd);
    // 检查用户名和密码
    const adminUser = await service.admin.adminUser.getAdminUserByName(request.loginName);
    let macAddr = '';
    if (adminUser) {
      if (adminUser.state != 1) {
        // 密码错误返回
        ctx.response.failByCode('1002', 200, '用户状态异常');
        return;
      }
      if (adminUser.loginPwd != encryPwd) {
        // 密码错误返回
        ctx.response.failByCode('1003');
        return;
      }
      // if (request.loginName != 'admin') {
      // 验证mac地址
      const allMacAddr = await sysMacAddrService.findAllMacAddr(this.app);
      macAddr = ctx.headers && ctx.headers.macaddr || '';
      if (!macAddr || !allMacAddr.map(obj => obj && obj.mac_addr).includes(macAddr)) {
        ctx.response.failByCode('0007', 403);
        return;
      }
      // }
      // 查询用户权限菜单
      const sysMenusTree = await service.admin.sysMenus.querySysMenusTreeByAdminUserId(adminUser.id);
      // 用户按钮权限列表
      const authoList = await service.admin.sysMenus.queryAuthoListByAdminUserId(adminUser.id);
      // 获取用户权限设置
      const adminUserRights = await service.admin.adminUser.queryAdminUserRightsByUserId(adminUser.id);
      // 生成token信息
      const token = await this.app.getToken({ 
        id: adminUser.id, 
        realName: adminUser.realName, 
        branchCode: adminUser.branchCode, 
        roles: authoList.userFunctionNameAuthoList, 
        userRights: adminUserRights, 
        macAddr,
      });
      // 赋值返回数据
      response.id = adminUser.id;
      response.adminUser = adminUser;
      response.token = token;
      response.sysMenusTree = sysMenusTree;
      response.roles = authoList.userControllerAuthoList;
      // 添加操作日志
      const des = `【${adminUser.realName}】在【${ctx.getDate_YYYY_MM_DD_HH_mm_ss()}】登录了系统`;
      ctx.writeSysOperationLogs('管理员登录', ctx.getSystemLogType('OTHER'), {
        curAdminUser: adminUser,
        des
      });
      ctx.response.success(response);
      return;
    }
    ctx.response.failByCode('1002');
  }

  async addAdminUser() {
    const {
      ctx,
      service
    } = this;
    // 检查请求参数并获得请求对象
    const request = ctx.request.getAndValidate_AddUserRequest();
    const result = await service.admin.adminUser.addAdminUser(request);
    if (result) {
      ctx.response.success(result);
      // 添加操作日志
      delete request.loginPwd;
      const des = `【${ctx.curAdminUser.realName}】在【${ctx.getDate_YYYY_MM_DD_HH_mm_ss()}】添加了账户【${request}】`;
      ctx.writeSysOperationLogs('添加管理员账户', ctx.getSystemLogType('CREATE'), { curAdminUser: ctx.curAdminUser, des, tableName: '管理员账户表' });
      return;
    }
    ctx.response.failByCode('1001');
  }

  // 删除用户信息 (逻辑删除)
  async deleteUser() {
    const { ctx, service } = this;
    // 检查请求参数并获得请求对象
    const request = ctx.request.getAndValidate_DeleteAdminUserRequest();
    const result = await service.admin.adminUser.deleteAdminUser(request.id);
    if (result) {
      ctx.response.success();
      // 添加操作日志
      const des = `【${ctx.curAdminUser.realName}】在【${ctx.getDate_YYYY_MM_DD_HH_mm_ss()}】删除管理员账户为【${request}】`;
      ctx.writeSysOperationLogs('删除管理员账户', ctx.getSystemLogType('DELETE'), { curAdminUser: ctx.curAdminUser, des });
      return;
    }
    ctx.response.fail('删除用户失败');
  }

  // 更新用户信息 
  async updateUser() {
    const { ctx, service } = this;
    // 检查请求参数并获得请求对象
    const request = ctx.request.getAndValidate_UpdateAdminUserRequest();
    const result = await service.admin.adminUser.updateAdminUser(request);
    if (result) {
      ctx.response.success();
      // 添加操作日志
      const des = `【${ctx.curAdminUser.realName}】在【${ctx.getDate_YYYY_MM_DD_HH_mm_ss()}】更新管理员账户信息【${request}】`;
      ctx.writeSysOperationLogs('更新管理员账户信息', ctx.getSystemLogType('UPDATE'), { curAdminUser: ctx.curAdminUser, des });
      return;
    }
    ctx.response.fail('更新用户失败');
  }

  async queryAdminUsersList() {
    const { ctx, service } = this;
    const response = adminUserReqAndResp.queryAdminUsersList.response();
    // 检查请求参数并获得请求对象
    const request = ctx.request.getAndValidate_QueryAdminUsersList();
    // 查询用户列表
    const adminUsersList = await service.admin.adminUser.queryAdminUsersList(
      request.loginName,
      request.branchCode,
      request.state,
      request.roleId,
      request.startDate,
      request.endDate,
      request.pageSize,
      request.pageIndex
    );
    // 查询用户列表总数据量
    const dataCount = await service.admin.adminUser.queryAdminUsersListCount(
      request.loginName,
      request.branchCode,
      request.state,
      request.roleId,
      request.startDate,
      request.endDate
    );
    if (adminUsersList) {
      response.pageCount = Math.ceil(dataCount / request.pageSize);
      response.dataCount = dataCount;
      response.adminUsersList = adminUsersList;
      ctx.response.success(response);
      // 添加操作日志
      ctx.writeSysOperationLogs('查询管理员账户列表', ctx.getSystemLogType('QUERY'), {
        tableName: '管理员账户表'
      });
      return;
    }
    response.pageCount = 0;
    response.dataCount = 0;
    response.adminUsersList = [];

    ctx.response.success(response);
    // 添加操作日志
    ctx.writeSysOperationLogs('查询管理员账户列表', ctx.getSystemLogType('QUERY'), {
      tableName: '管理员账户表'
    });
  }

  // 查询用户详细信息
  async findByIdAdminUserInfo() {
    const {
      ctx,
      service
    } = this;
    const id = ctx.request.body.id;
    const result = await service.admin.adminUser.findByIdAdminUserInfo(id);
    ctx.logger.debug('查询到的用户信息：', result);
    if (!result) {
      ctx.response.fail('未找到您要查找的用户信息。');
      return;
    }
    ctx.response.success(result);
    const des = `【${ctx.curAdminUser.realName}】在【${ctx.getDate_YYYY_MM_DD_HH_mm_ss()}】根据id查询用户【${result.id}】的详细信息`;
    ctx.writeSysOperationLogs('根据id查询用户详细信息', ctx.getSystemLogType('QUERY'), {
      curAdminUser: ctx.curAdminUser,
      des
    });
  }

  async getLoginUserDetail() {
    const {
      ctx,
      service
    } = this;
    const {
      id,
      realName
    } = ctx.curAdminUser;
    const sysMenusTree = await service.admin.sysMenus.querySysMenusTreeByAdminUserId(id);
    const adminUser = await service.admin.adminUser.findByIdAdminUserInfo(id);
    // 用户按钮权限列表
    const authoList = await service.admin.sysMenus.queryAuthoListByAdminUserId(id);

    ctx.response.success({
      sysMenusTree,
      adminUser,
      roles: authoList.userControllerAuthoList
    });
    // // 添加操作日志
    // const des = `【${realName}】在【${ctx.getDate_YYYY_MM_DD_HH_mm_ss()}】登录了系统`;
    // ctx.writeSysOperationLogs('管理员免密登录', ctx.getSystemLogType('OTHER'), { des });
  }

  async updatePwd() {
    const {
      ctx,
      service
    } = this;
    const {
      id,
      realName
    } = ctx.curAdminUser;
    const loginPwd = ctx.request.body.loginPwd;
    if (!id || !loginPwd) {
      ctx.response.fail('更新用户失败');
      return;
    }
    await service.admin.adminUser.updatePwd(id, loginPwd);
    ctx.response.success();
    const des = `【${ctx.curAdminUser.realName}】在【${ctx.getDate_YYYY_MM_DD_HH_mm_ss()}】更新了自己的账号密码】`;
    ctx.writeSysOperationLogs('自更新密码', ctx.getSystemLogType('UPDATE'), {
      curAdminUser: ctx.curAdminUser,
      des
    });
  }
}

module.exports = LoginController;
